<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item style='display:none' name='id'>
            <a-input type='hidden' v-model:value='formData.id' />
        </a-form-item>
        <a-form-item label='父分类' name='parentId' :rules="[{required : true, message : '请选择父分类'}]">
                <a-tree-select show-search v-model:value='formData.parentId' :tree-data='parentOptions' :field-names='{children : "children", label : "name", value : "id"}'></a-tree-select>
        </a-form-item>
        <a-form-item label='名称' name='name' :rules="[{required : true, message : '请填写名称'}]">
            <a-input type='text' v-model:value='formData.name' />
        </a-form-item>
        <a-form-item v-if="formData.parentId == 0" label='服务对象' name='related'>
            <a-select v-model:value="formData.related" :options="relatedOptions"  mode="multiple" style="width: 100%" :field-names="{ label: 'name', value: 'id'}" />
        </a-form-item>
        <a-form-item label='前台显示' name='enable'>
            <a-switch v-model:checked='formData.enable' checked-children='显示' un-checked-children='不显示'/>
        </a-form-item>
        <a-form-item label='排序' name='sort'>
            <a-input type='number' v-model:value='formData.sort' />
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
        import { saveApi, optionsApi } from '@/api/apps/Category';
import { dictionaryItemByCategoryApi } from '@/api/system/Dictionary';
import { recursionFn } from '@/utils';
        import { nextTick, ref } from 'vue';


    const props = defineProps<{
        row? : any;
        parentId:number;
    }>()

    const formRef = ref()

    
    const formData = ref({
        id : 0,
        type : '',
        name : '',
        parentId : 0,
        related : [],
        sort : 0,
        enable : true,
    })


    if(props.row) {
        for(let k in props.row) {
            if(k in formData.value) {
                if(k == 'related') {
                    formData.value[k] = props.row[k] || []
                }else {
                    formData.value[k] = props.row[k]
                }
                
            }
        }
    }else {
        formData.value.parentId = props.parentId
    }




    async function submit() {
        let params  = await formRef.value.validate()
        if('sort' in params && params.sort === '') {
            params.sort = 0
        }


        return saveApi(params)
    }

    const parentOptions = ref<any[]>([{id : 0, name : '顶级分类'}])
    const relatedOptions = ref<any[]>([])
    
    defineExpose({
        submit
    })

    optionsApi().then(res => {
        if(res.data) {
            parentOptions.value.push(...recursionFn(res.data, Math.min(...res.data.map(r => r.parentId)), 'id', 'parentId', 'children'))
        }
    })

    dictionaryItemByCategoryApi('PORTAL_USER_TYPE').then(res => {
        if(res.data) {
            relatedOptions.value = res.data
        }
    })
</script>